// templates/deliver/pages/orderAll/orderAll.js
import Toast from '@vant/weapp/toast/toast';

const { authorization } = require('../../../../utils/location')

// 获取当前位置
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderAll : [],  //查询全部数据
        activeNames: ['0'], //点击折叠

        driver_orders: [],
        store: {},
        //Map
        latitude: 0,
        longitude: 0,
        scale: 12.1, //3-20
        is_edit: false,
        update_location_text: '调整定位',

        is_update_location: false,

        update_type: -1,
        markers: [],

        polyline: [],
        center_location: undefined,

        //备注以及上传照片相关
        show_popup: false,
        store_name: '',
        store_remark: '',
        store_logo: [],
        store_photo: [],
        max_size: 1048576 * 3, //单图片大小

        //图片预览
        indicatordots:true,
        //是否显示面板指示点
        autoplay:false, //是否自动切换
        interval: 5000, //自动切换时间间隔
        duration: 500, //滑动动画时长
        color:'#ffffff', //当前选中的指示点颜色
        height:'',

        view_delivery_man_id: 0,
        view_driver_name: '',
        view_delivery_district_id: 0
        //swiper高度
    },

    switch_show_center: async function (e) {
        if (this.data.is_edit) {
            this.setData({
                'is_edit': false,
                'scale': 12,
                'update_location_text': '调整定位'
            })


            this.map = wx.createMapContext('locationM', this)

            if (this.data.longitude === undefined) {
                let res = await authorization()
                console.log(res)
            }

            let res = await authorization()
            console.log("authorization res", res)

            this.map.moveToLocation({
                longitude: Number(this.data.longitude),
                latitude: Number(this.data.latitude),
                success: function () {
                    console.log("成功将地图中心移到定位点")
                }
            })
            Toast('结束定位调整。')
        } else {
            this.setData({
                'scale': 18,
                'is_edit': true,
                'update_location_text': '结束调整'
            })

            let driver_order = this.data.driver_orders[0]
            let order_location = driver_order['order_location']
            let location_parts = order_location.split(',')

            this.map = wx.createMapContext('locationM', this)
            this.map.moveToLocation({
                longitude: Number(location_parts[0]),
                latitude: Number(location_parts[1]),
                success: function () {
                    console.log("成功将地图中心移到定位点")
                }
            })

            Toast('拖动要定位的位置到中心知识点，然后更新对应的定位即可。')

        }
    },

    binddelivery_districtchange: function (e) {
        if (!this.data.is_edit) {
            return;
        }
        if (!(e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag'))) {
            return
        }
        let center_location = e.detail.centerLocation;
        console.log('center_location:', center_location)
        this.setData({
            'center_location': center_location
        })
    },

    bindmarkertap: function (e){
        /*
        locationUtils.getLocation().then(res => {
            console.log('当前所在位置的经纬度为：')
            console.log(res.latitude,res.longitude)
        })

        */
    },

    ballPopup(e) {
        //let id = e.currentTarget.dataset.id //获取传递的id参数
        //let ordername = e.currentTarget.dataset.ordername
        this.setData({
            show_popup: true,
        }) //打开弹窗
    },
    onPopupClose() {
        this.setData({
            show_popup: false,
        })
    },

    /* 上传文件查看图片大小 */
    imgSize(event) {
        let imgMax = this.data.store_image_max_size; //获取默认上传文件大小
        const {
            file
        } = event.detail; //获取上传文件数组
        for (let i = 0; i < file.length; i++) {
            if (file[i].size > imgMax) {
                Toast('大小超过2MB~')
            }
        }
    },

    afterReadLogo(event) {
        this.afterRead(event, 1)
    },
    afterReadPhoto(event) {
        this.afterRead(event, 2)
    },

    /* 上传文件后事件，处理照片放入OSS回显 */
    afterRead(event, image_type) {
        // console.log('上传触发1')
        let that = this
        const {
            file
        } = event.detail; //获取上传文件数组
        for (let i = 0; i < file.length; i++) {
            /* 开始上传 */
            wx.uploadFile({
                url: app.globalData.URL + '/deliver.Upload/uploadImg',
                filePath: file[i]['url'], //传递文件
                name: 'image', //获取照片信息的名称
                success(res) {
                    // console.log('上传触发2')
                    let result = JSON.parse(res.data) //传过来的是json 需要转换成对象

                    console.log('result:', image_type, result)
                    const images = image_type === 1 ? that.data.store_logo : that.data.store_photo
                    console.log('images', images,)
                    images.push({url: result.data})
                    that.setData({
                        [image_type === 1 ? 'store_logo' : 'store_photo']: images
                    })
                }
            })
        }
    },
    /**
     * 删除上传的照片
     */

    imgDeleteLogo(event) {
        this.imgDelete(event, 1)
    },
    imgDeletePhoto(event) {
        this.imgDelete(event, 2)
    },
    imgDelete(event, image_type) {
        let that = this;
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.URL + '/deliver.Upload/deleteImg',
            method: 'DELETE',
            header: {},
            data: {path: urlPath},
            success: res => {
                // console.log(res)
                if (res.data.code === 1) {
                    //'删除图片失败'
                } else {
                    const images = image_type === 1 ? that.data.store_logo : that.data.store_photo
                    images.splice(event.detail.index, 1)
                    that.setData({
                        [image_type === 1 ? 'store_logo' : 'store_photo']: images
                    })
                }
            }
        })
    },


    save_store_location: function () {
        this.save_location(0)
        Toast('已更新店铺定位')
    },
    save_tricycle_stop_location: function () {
        this.save_location(1)
        Toast('已更新三路车驻车点定位')
    },
    save_vehicle_stop_location: function () {
        this.save_location(2)
        Toast('已更新货车驻车点定位')
    },

    submit_store_remark(e) {
        let that = this
        let url = app.globalData.URL
        let mall_id = app.globalData.mall_id //获取主商城id
        let driver_order = that.data.driver_orders[0]
        let user_id = driver_order['user_id']
        let store_id = driver_order['store_id']
        let order_location = driver_order['order_location']

        let store_logo = that.data.store_logo
        let store_photo = that.data.store_photo

        let store_remark = e.detail.value.store_remark
        let store_name = e.detail.value.store_name

        wx.request({
            url: url + '/deliver.Store/storeRemark',
            data: {
                mall_id,
                user_id,
                store_name,
                store_logo,
                store_photo,
                store_remark,
                order_location,
                store_id
            },
            method: "POST",
            success: res => {
                // console.log(res)
                if (res.data.code === 0) {
                    Toast('提交成功~')
                    that.onPopupClose()
                } else {
                    Toast('提交失败~')
                }
            }
        })
    },


    save_location: function (location_type) {
        let that = this
        if (that.data.driver_orders.length === 0) {
            return;
        }
        let driver_order = that.data.driver_orders[0]
        let store_id = driver_order['store_id']
        let user_id = driver_order['user_id']
        let order_location = driver_order['order_location']
        let order_phone = driver_order['order_phone']
        let order_address = driver_order['order_address']
        let center_location = that.data.center_location


        wx.request({
            url: app.globalData.URL + '/deliver.location/updateStoreLocation',
            method: 'POST',
            data: {
                mall_id: app.globalData.mall_id, //主商城id
                update_location: center_location.longitude + "," + center_location.latitude,
                location_type: location_type,
                user_id: user_id,
                order_location: order_location,
                order_address: order_address,
                order_phone: order_phone,
                store_id: store_id
            },
            success(res) {
                //console.log(res)
                if (res.data.code === 0) {

                    //console.log(res.data.message)
                }
            }
        });
        /*
        if (center != null) {
            let marker = {
                iconPath: "../../img/map-center.png",
                id: 0,
                latitude: center.latitude,
                longitude: center.longitude,
                width: 27,
                height: 87,
                callout: {
                    content: '选中位置',
                    fontSize: 14,
                    padding: true,
                    color: '#444',
                    display: 'ALWAYS',
                    textAlign: 'center',
                    borderRadius: 5,
                    bgColor: '#ffffff'
                },
            };
            let markers = that.data.markers || []; // 获取当前页面的markers数组，若为空则初始化为空数组
            let found = false; // 判断是否找到 id 为 0 的 marker
            for (let i = 0; i < markers.length; i++) {
                if (markers[i].id === 0) {
                    markers[i] = marker; // 替换已有的 id 为 0 的 marker
                    found = true;
                    break;
                }
            }
            if (!found) {
                markers.push(marker); // 若未找到则添加新的 marker
            }
            that.setData({ markers: markers }); // 更新页面数据中的markers数组
        }
        */
    },

    goheight:function (e) {
        var width = wx.getSystemInfoSync().windowWidth
        //获取可使用窗口宽度
        var imgheight = e.detail.height
        //获取图片实际高度
        var imgwidth = e.detail.width
        //获取图片实际宽度
        var height = width * imgheight / imgwidth +"px"
        //计算等比swiper高度
        this.setData({
            height: height
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
        let view_driver_name = ''
        let view_delivery_district_id = 0
        if (view_delivery_man_id > 0) {
            view_driver_name = wx.getStorageSync('view_driver_name')
            view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
        }

        this.setData({
            view_delivery_man_id,
            view_driver_name,
            view_delivery_district_id
        })

        let delivery_man = wx.getStorageSync('delivery_man')
        let that = this
        wx.getLocation({
            type: "gcj02",
            success(res) {

                let xian_latitude = 34.26986287676798
                let xian_longitude =108.9471324706426

                let map_latitude = xian_latitude
                let map_longitude = xian_longitude
                if (that.getDistance(xian_latitude, xian_longitude, res.latitude, res.longitude) < 300) {
                    map_latitude = res.latitude
                    map_longitude = res.longitude
                }

                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                })
            }
        })


        const eventChannal = this.getOpenerEventChannel();
        eventChannal.on('orderAll',function (res){
            //
            let data = JSON.parse(res)
            let driver_orders = data['driver_orders'] || []
            console.log('orderAll data', data)
            let location_temp = {}
            for (let i = 0; i < driver_orders.length; i++) {
                location_temp[driver_orders[i]['order_location']] = true
            }
            let point = (driver_orders[0]['order_location']).split(',')

            let markers=[]

            let store_marker = {
                iconPath: "../../img/icon-hc.png",
                id: driver_orders[0].id,
                latitude: Number(point[1]),
                longitude: Number(point[0]),
                width: 23,
                height: 23,
                callout: {
                    content: driver_orders[0].order_name,
                    fontSize: 14,
                    padding: true,
                    color: '#ffffff',
                    display: 'ALWAYS',
                    textAlign: 'center',
                    borderRadius: 10,
                    bgColor: '#0077ffbe'
                },
            }
            markers.push(store_marker)

            let tricycle_stop_marker = {}
            let vehicle_stop_marker = {}

            let store = data['store']
            let store_logo = []
            let store_photo = []
            let store_name = ''
            let store_remark = ''
            if (store) {
                //store['location'] = "108.82880158793637,34.17408247997613"
                if (store['location'].indexOf(',') > 0) {
                    let location = store['location'].split(',')
                    store_marker.latitude = Number(location[1])
                    store_marker.longitude = Number(location[0])
                }
                console.log('store', store)

                if (store['logo']) {
                    store_logo = store['logo']
                }
                if (store['photo']) {
                    store_photo = store['photo']
                }

                if (store['store_name']) {
                    store_name = store['store_name']
                }

                if (store['remark']) {
                    store_remark = store['remark']
                }

                if (store['tricycle_stop_location'].indexOf(',') > 0) {
                    let location = store['tricycle_stop_location'].split(',')
                    tricycle_stop_marker = {
                        iconPath: "../../img/tricycle.png",
                        id: 1,
                        latitude: Number(location[1]),
                        longitude: Number(location[0]),
                        width: 12,
                        height: 6,
                        callout: {
                            content: '三轮停车点',
                            fontSize: 14,
                            padding: true,
                            color: '#ffffff',
                            display: 'ALWAYS',
                            textAlign: 'center',
                            borderRadius: 10,
                            bgColor: '#0077ffbe'
                        },
                    }
                }

                if (store['vehicle_stop_location'].indexOf(',') > 0) {
                    let location = store['vehicle_stop_location'].split(',')
                    vehicle_stop_marker = {
                        iconPath: "../../img/truck.png",
                        id: 2,
                        latitude: Number(location[1]),
                        longitude: Number(location[0]),
                        width: 12,
                        height: 6,
                        callout: {
                            content: '货车停车点',
                            fontSize: 14,
                            padding: true,
                            color: '#ffffff',
                            display: 'ALWAYS',
                            textAlign: 'center',
                            borderRadius: 10,
                            bgColor: '#0077ffbe'
                        },
                    }
                }
            }
            markers.push(store_marker)
            let polyline = []
            if (Object.keys(tricycle_stop_marker).length > 0) {
                markers.push(tricycle_stop_marker)
                polyline.push({
                    points: [
                        {longitude: tricycle_stop_marker.longitude, latitude: tricycle_stop_marker.latitude},
                        {longitude: store_marker.longitude, latitude: store_marker.latitude},
                    ],
                    color: "#FF0000DD",
                    width: 2,
                    dottedLine: true,
                })
            }
            if (Object.keys(vehicle_stop_marker).length > 0) {
                markers.push(vehicle_stop_marker)
                polyline.push({
                    points: [
                        {longitude: vehicle_stop_marker.longitude, latitude: vehicle_stop_marker.latitude},
                        {longitude: store_marker.longitude, latitude: store_marker.latitude},
                    ],
                    color: "#FF0000DD",
                    width: 2,
                    dottedLine: true,
                })
            }


            that.setData({
                orderAll: data['mall_orders'],
                driver_orders: data['driver_orders'],
                store: data['store'],
                markers: markers,
                polyline: polyline,
                store_photo: store_photo,
                store_logo: store_logo,
                store_name: store_name,
                store_remark: store_remark
            })
        })  
       
    },

    // 经纬度计算距离
    getDistance(lat1, lng1, lat2, lng2) {

        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137; // EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return parseFloat(s);
    },

    on_travel(e) {
        console.log('store:', this.data.store)
        // console.log(e)
        let location = ''
        let location_id = e.currentTarget.dataset.location_id //定位ID

        let store_name = '未标注店铺'
        let address = this.data.orderAll[0].address

        if (this.data.store) {
            if (this.data.store.store_name.length > 0) {
                store_name = this.data.store.store_name
            }

            if (this.data.store.remark.length > 0) {
                address += ' *备注：' + this.data.store.remark
            }
            if (location_id === "0") {
                location = this.data.store.location
                store_name = '[门店]' + store_name
            } else if (location_id === "1") {
                location = this.data.store.tricycle_stop_location
                store_name = '[三轮车驻车点]' + store_name
            } else if (location_id === "2") {
                location = this.data.store.vehicle_stop_location
                store_name = '[货车驻车点]' + store_name
            }
        }


        if (location.length === 0) {
            location = this.data.orderAll[0].location
        }
        console.log('location:', location)

        if (location.indexOf(',')) {
            let location_parts = location.split(',')
            wx.openLocation({
                name: store_name,
                address: address,
                longitude: Number(location_parts[0]),
                latitude: Number(location_parts[1]),
            })
        }
    },
/**
     * 默认打开折叠
     */
    onChange(event){
        console.log(event.detail)
        this.setData({
            activeNames: event.detail,
          });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {


    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    //这个函数是一开始点击事件触发的：
    async authorization() {
        let self = this
        try {
            await this.getWxLocation()//等待
        } catch (error) {
            Model({
                title: '温馨提示',
                tip: '获取权限失败，需要获取您的地理位置才能为您提供更好的服务！是否授权获取地理位置？',
                showCancel: true,
                confirmText: '前往设置',
                cancelText: '取消',
                sureCall() {
                    self.toSetting()
                },
                cancelCall() {}
            })
            return
        }
    },

    getWxLocation() {
        let that = this
        if (that.is_update_location) {
            that.setData({
                'is_update_location': false,
                'update_location_text': '获取定位',
            })
            return
        }
        wx.showLoading({
            title: '定位中...',
            mask: true,
        })
        return new Promise((resolve, reject) => {
            let _locationChangeFn = (res) => {
                wx.hideLoading()
                wx.offLocationChange(_locationChangeFn)
            }
            wx.startLocationUpdate({
                success: (res) => {
                    wx.onLocationChange(_locationChangeFn)
                    resolve()
                },
                fail: (err) => {
                    console.log('获取当前位置失败', err)
                    wx.hideLoading()
                    reject()
                }
            })
        })
    },
    toSetting() {
        let self = this
        wx.openSetting({
            success(res) {
                console.log(res)
                if (res.authSetting["scope.userLocation"]) {
                    // res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息，此时调用getlocation可以拿到信息
                    self.authorization()
                }
            }
        })
    },

})